<!DOCTYPE html>
<html>
  <head>
      <!-- Notes: This should be open in its original path-->
      <meta charset="utf-8">
      <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
      <link rel="stylesheet" href="../script/semantic/semantic.min.css">
      <script src="../script/jquery-3.6.0.min.js"></script>
      <script src="../script/semantic/semantic.min.js"></script>
      <script src="../script/utils.js"></script>
      <style>
        #refreshAccessRuleListBtn{
            position: absolute;
            top: 0.4em;
            right: 1em;
        }

      </style>
  </head>
  <body>
    <link rel="stylesheet" href="../darktheme.css">
    <script src="../script/darktheme.js"></script>
    <br>
    <div class="ui container">
        <div class="ui header">
            <div class="content">
                Access Rule Editor
                <div class="sub header">Create, Edit or Remove Access Rules</div>
            </div>
        </div>
        <div class="ui divider"></div>
        <div class="ui top attached tabular menu">
            <a class="active item" data-tab="new"><i class="ui green add icon"></i> New</a>
            <a class="item" data-tab="edit"><i class="ui grey edit icon"></i> Edit</a>
        </div>
        <div class="ui bottom attached active tab segment" data-tab="new">
            <p>Create a new Access Rule</p>
            <form class="ui form" id="accessRuleForm">
                <div class="field">
                    <label>Rule Name</label>
                    <input type="text" name="accessRuleName" placeholder="Rule Name" required>
                </div>
                <div class="field">
                    <label>Description</label>
                    <textarea name="description" placeholder="Description" required></textarea>
                </div>
                <button class="ui basic button" type="submit"><i class="ui green add icon"></i> Create</button>
            </form>
        <br>
        </div>
        <div class="ui bottom attached tab segment" data-tab="edit">
            <p>Select an Access Rule to edit</p>
            <button id="refreshAccessRuleListBtn" class="ui circular basic icon button" onclick="reloadAccessRuleList()"><i class="ui green refresh icon"></i></button>
            <div class="ui selection fluid dropdown" id="accessRuleSelector">
                <input type="hidden" name="targetAccessRule" value="default">
                <i class="dropdown icon"></i>
                <div class="default text"></div>
                <div class="menu" id="accessRuleList">
                    <div class="item" data-value="default"><i class="ui yellow star icon"></i> Default</div>
                </div>
            </div>
            <br>
            <form class="ui form" id="modifyRuleInfo">
                <div class="disabled field">
                    <label>Rule ID</label>
                    <input type="text" name="accessRuleUUID">
                </div>
                <div class="field">
                    <label>Rule Name</label>
                    <input type="text" name="accessRuleName" placeholder="Rule Name" required>
                </div>
                <div class="field">
                    <label>Description</label>
                    <textarea name="description" placeholder="Description" required></textarea>
                </div>
                <button class="ui basic button" type="submit"><i class="ui green save icon"></i> Save Changes</button>
                <button class="ui basic button" onclick="removeAccessRule(event);"><i class="ui red trash icon"></i> Remove Rule</button>
            </form>
        </div>
        <br>
        <button class="ui basic button"  style="float: right;" onclick="parent.hideSideWrapper();"><i class="remove icon"></i> Close</button>
        <br><br><br>
  </div>

  <script>
    let accessRuleList = [];
    $('.dropdown').dropdown();
    $('.menu .item').tab();

    function handleCreateNewAccessRule(event) {
        event.preventDefault(); // Prevent the default form submission
        const formData = new FormData(event.target);
        const accessRuleName = formData.get('accessRuleName');
        const description = formData.get('description');

        console.log('Access Rule Name:', accessRuleName);
        console.log('Description:', description);
        
        $("#accessRuleForm input[name='accessRuleName']").val("");
        $("#accessRuleForm textarea[name='description']").val("");

        $.cjax({
            url: "/api/access/create",
            method: "POST",
            data: {
                "name": accessRuleName,
                "desc": description
            },
            success: function(data){
                if (data.error != undefined){
                    parent.msgbox(data.error, false);
                }else{
                    parent.msgbox("Access Rule Created", true);
                    reloadAccessRuleList();
                    if (parent != undefined && parent.reloadAccessRules != undefined){
                        parent.reloadAccessRules();
                    }
                }
            }
        })
    }

    //Handle on change of the dropdown selection
    function handleSelectEditingAccessRule(){
        const selectedValue = document.querySelector('#accessRuleSelector').querySelector('input').value;
        console.log('Selected Value:', selectedValue);
        //Load the information from list
        loadAccessRuleInfoIntoEditFields(selectedValue);
    }

    //Load the access rules information into the fields
    function loadAccessRuleInfoIntoEditFields(targetAccessRuleUUID){
        var targetAccessRule = undefined;
        for (var i = 0; i < accessRuleList.length; i++){
            let thisAccessRule = accessRuleList[i];
            if (thisAccessRule.ID == targetAccessRuleUUID){
                targetAccessRule = thisAccessRule;
            }
        }

        if (targetAccessRule == undefined){
            //Target exists rule no longer exists
            return;
        }

        let accessRuleID = targetAccessRule.ID;
        let accessRuleName = targetAccessRule.Name;
        let accessRuleDesc = targetAccessRule.Desc;

        //Load the information into the form input field
         //Load the information into the form input field
        document.querySelector('#modifyRuleInfo input[name="accessRuleUUID"]').value = accessRuleID;
        document.querySelector('#modifyRuleInfo input[name="accessRuleName"]').value = accessRuleName;
        document.querySelector('#modifyRuleInfo textarea[name="description"]').value = accessRuleDesc;
    }

    //Bind events to modify rule form
    document.getElementById('modifyRuleInfo').addEventListener('submit', function(event){
        event.preventDefault(); // Prevent the default form submission

        const accessRuleUUID = document.querySelector('#modifyRuleInfo input[name="accessRuleUUID"]').value;
        const accessRuleName = document.querySelector('#modifyRuleInfo input[name="accessRuleName"]').value;
        const description = document.querySelector('#modifyRuleInfo textarea[name="description"]').value;

        
        console.log('Access Rule UUID:', accessRuleUUID);
        console.log('Access Rule Name:', accessRuleName);
        console.log('Description:', description);

        $.cjax({
            url: "/api/access/update",
            method: "POST",
            data: {
                "id":accessRuleUUID,
                "name":accessRuleName,
                "desc":description
            },
            success: function(data){
                if (data.error != undefined){
                    parent.msgbox(data.error, false);
                }else{
                    parent.msgbox("Access rule updated", true);
                    initAccessRuleList(function(){
                        $("#accessRuleSelector").dropdown("set selected", accessRuleUUID);
                        loadAccessRuleInfoIntoEditFields(accessRuleUUID);
                    });
                    if (parent != undefined && parent.reloadAccessRules != undefined){
                        parent.reloadAccessRules();
                    }
                }
            }
        })
    });

    function initAccessRuleList(callback=undefined){
        $.get("/api/access/list", function(data){
            if (data.error == undefined){
                $("#accessRuleList").html("");
                data.forEach(function(rule){
                    let icon = `<i class="ui grey filter icon"></i>`;
                    if (rule.ID == "default"){
                        icon = `<i class="ui yellow star icon"></i>`;
                    }else if (rule.BlacklistEnabled && !rule.WhitelistEnabled){
                        //This is a blacklist filter
                        icon = `<i class="ui red filter icon"></i>`;
                    }else if (rule.WhitelistEnabled && !rule.BlacklistEnabled){
                        //This is a whitelist filter
                        icon = `<i class="ui green filter icon"></i>`;
                    }
                    $("#accessRuleList").append(`<div class="item" data-value="${rule.ID}">${icon} ${rule.Name}</div>`);
                });
                accessRuleList = data;
                $(".dropdown").dropdown();
                if (callback != undefined){
                    callback();
                }
            }
        })
    }
    initAccessRuleList(function(){
        $("#accessRuleSelector").dropdown("set selected", "default");
        loadAccessRuleInfoIntoEditFields("default");
    });

    function reloadAccessRuleList(){
        initAccessRuleList(function(){
            $("#accessRuleSelector").dropdown("set selected", "default");
            loadAccessRuleInfoIntoEditFields("default");
        });
    }

    function removeAccessRule(event){
        event.preventDefault();
        event.stopImmediatePropagation();

        let accessRuleUUID = $("#modifyRuleInfo input[name='accessRuleUUID']").val();
        if (accessRuleUUID == ""){
            return;
        }
        if (accessRuleUUID == "default"){
            parent.msgbox("Default access rule cannot be removed", false);
            return;
        }
        let accessRuleName = $("#modifyRuleInfo input[name='accessRuleName']").val();
        if (confirm("Confirm removing access rule " + accessRuleName + "?")){
            $.cjax({
                url: "/api/access/remove",
                data: {
                    "id": accessRuleUUID
                },
                method: "POST",
                success: function(data){
                    if (data.error != undefined){
                        parent.msgbox(data.error, false);
                    }else{
                        parent.msgbox("Access rule removed", true);
                        reloadAccessRuleList();
                        if (parent != undefined && parent.reloadAccessRules != undefined){
                            parent.reloadAccessRules();
                        }
                    }
                }
            })
        }
    }

    document.getElementById('accessRuleSelector').addEventListener('change', handleSelectEditingAccessRule);
    document.getElementById('accessRuleForm').addEventListener('submit', handleCreateNewAccessRule);

  </script>
</body>
</html>
